import axios, { type AxiosInstance, type AxiosResponse, type AxiosError, type InternalAxiosRequestConfig } from 'axios';

import { showToast } from 'vant';
const service: AxiosInstance = axios.create({
  baseURL: 'https://youyi-api.itheima.net/',
  timeout: 5000,
  withCredentials: true,
  headers: {
    Authorization: localStorage.getItem('token')
  }
});

// 添加请求拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, (error: AxiosError) => {
  // ElMessage.error(error.message);
  return Promise.reject(error)
})


// 添加响应拦截器
service.interceptors.response.use((response: AxiosResponse) => {
  let { message, code, data } = response.data
  switch (code) {
    case 200:
      showToast(message)
      break;
    case 401:
      showToast(message)
      break;
    case 201:
      showToast(message)
      break;
    case 204:
      showToast(message)
      break;
    case 400:
      showToast(message)
      break;
    case 403:
      showToast(message)
      break;
    case 404:
      showToast(message)
      break;
    case 422:
      showToast(message)
      break;
    case 500:
      showToast(message)
      break;
    case 10000:
      showToast(message)
  }
  return response // 返回数据
}, (error: AxiosError) => {
  // 超时处理
  if (JSON.stringify(error).includes('timeout')) {
    // ElMessage.error('服务器响应超时，请刷新当前页')
    showToast('服务器响应超时，请刷新当前页')
  }
  return Promise.reject(error)
})
export default service